<template>
  <div>
    <GlobalTop></GlobalTop>

    <!--搜索-->
    <div class="search">
      <div class="my_search">
        <div class="icon">
          <van-icon name="search" />
        </div>
        <input
          type="text"
          v-model="inpVal"
          id="myInput"
          class="input"
          placeholder="搜索歌曲、歌手、专辑"
          @input="handleInput"
          :maxlength="maxLength"
          @keyup.enter="enter"
        />
        <button v-if="inpVal" @click="clearInput">
          <van-icon name="close" />
        </button>
      </div>
    </div>

    <!--加载中...-->
    <GlobalLoading v-if="isShowLoadingHotSearch"></GlobalLoading>

    <!--热门搜索-->
    <div class="hot-search" v-if="isShow">
      <div class="title">热门搜索</div>
      <div class="wrapper">
        <div
          class="song-title"
          :class="{ actived: currentIndex == index }"
          v-for="(hots, index) in hotSearchList"
          :key="hots.hotSearchId"
          @click="search(hots.first)"
        >
          {{ hots.first }}
        </div>
      </div>
    </div>

    <!--搜索结果-->
    <div class="search-list" v-if="!isShow">
      <div class="name">搜索"{{ inpVal }}"</div>
    </div>

    <!--加载中...-->
    <GlobalLoading v-if="isShowLoadingSearchList"></GlobalLoading>

    <div class="bestFit" v-if="showContent">
      <div class="title">最佳匹配</div>

      <!--歌手栏-->
      <div
        class="singer"
        :class="{ actived: currentIndex == index }"
        v-for="(singerItem, index) in singerHurdle"
        :key="singerItem.singerId"
        @click="singerList(index)"
      >
        <div class="icon">
          <img :src="singerItem.img1v1Url" />
        </div>
        <div class="name">
          {{ singerItem.occupation }} : {{ singerItem.name }}
        </div>
        <div class="enter">
          <van-icon name="arrow" />
        </div>
      </div>

      <!--歌单栏-->
      <div
        class="song"
        :class="{ actived: currentIndex == index }"
        v-for="(songItem, index) in songHurdle"
        :key="songItem.songId"
        @click="songList(index)"
      >
        <div class="icon">
          <img :src="songItem.coverImgUrl" />
        </div>
        <div class="name">
          歌单：{{ songItem.name }}
          <div class="author">by:{{ songItem.creator.nickname }}</div>
        </div>
        <div class="enter">
          <van-icon name="arrow" />
        </div>
      </div>

      <!--专辑栏-->
      <div
        class="collection"
        :class="{ actived: currentIndex == index }"
        v-for="(collectionItem, index) in collectionHurdle"
        :key="collectionItem.collectionId"
        @click="collection(index)"
      >
        <div class="icon">
          <img :src="collectionItem.blurPicUrl" />
        </div>
        <div class="name">
          专辑：{{ collectionItem.name }}
          <div class="author">by:{{ collectionItem.artist.name }}</div>
        </div>
        <div class="enter">
          <van-icon name="arrow" />
        </div>
      </div>
      <GlobalSongs :blockList="blockList"></GlobalSongs>
    </div>

    <!--搜索列表-->
    <div class="search-list" v-if="!isShow">
      <div
        class="list"
        :class="{ actived: currentIndex == index }"
        v-for="(allMatch, index) in searchList"
        :key="allMatch.searchId"
      >
        <div class="icon">
          <van-icon name="search" style="margin: 10px 15px" size="20" />
        </div>
        <div class="info" @click="search(allMatch.keyword)">
          {{ allMatch.keyword }}
        </div>
      </div>
      <div class="mistake">{{ mistake }}</div>
    </div>

    <!--历史记录-->
    <div class="history" v-if="isShow">
      <div class="list" v-for="(input, index) in inputHistory" :key="index">
        <div class="icon">
          <van-icon name="clock-o" size="20" />
        </div>
        <div class="record">
          <div class="my-record" @click="search(input)">
            {{ input }}
          </div>
          <button @click="clearHistory(index)">
            <van-icon name="cross" />
          </button>
        </div>
      </div>
    </div>
  </div>
</template>
  
<script setup>
import GlobalSongs from "@/components/GlobalSongs.vue";
import GlobalTop from "@/components/GlobalTop.vue";
import GlobalLoading from "@/components/GlobalLoading.vue";
import { watch, onMounted, ref, computed } from "vue";
import { showToast } from "vant";
import { useMainStore } from "@/pinia/store.ts";
import router from "@/router/routes";
import { useRoute } from "vue-router";
import axios from "axios";
import {
  getSearchApi,
  getHotSearchApi,
  getMultiMatchApi,
  getCloudSearchApi,
} from "@/request/api/home.ts";

const currentIndex = ref(0);
const mainStore = useMainStore();
const route = useRoute();
const hotSearchList = ref([]); // 热门搜索
const searchList = ref([]); // 搜索列表
const singerHurdle = ref([]); // 歌手栏
const songHurdle = ref([]); // 歌单栏
const collectionHurdle = ref([]); // 专辑栏
const blockList = ref([]); //歌曲列表
// const inputHistory = ref([]); // 历史记录
const inputHistory = ref(
  JSON.parse(localStorage.getItem(LOCALSTORAGE_KEY) || "[]")
);
const LOCALSTORAGE_KEY = "inputHistory_data";
const mistake = ref("");
const inpVal = ref("");
const value = ref("");
const maxLength = 20; // 设置最大字数限制
const isShow = ref(true); // 搜索结果
const showContent = ref(false); // 最佳匹配
const isShowLoadingHotSearch = ref(false); //热门搜索加载
const isShowLoadingSearchList = ref(false); //最佳匹配加载

const getSearch = async () => {
  const res = await getSearchApi({
    keywords: inpVal.value,
    type: "mobile",
  });
  if (res.data.result.allMatch) {
    searchList.value = res.data.result.allMatch;
    mistake.value = "";
    console.log("搜索到数据：", searchList.value);
  } else {
    searchList.value = [];
    mistake.value = "查无数据";
    console.log(mistake.value);
  }
};
const getHotSearch = async () => {
  const res = await getHotSearchApi();
  console.log("热门搜索：", res.data);
  hotSearchList.value = res.data.result.hots;
};
const getMultiMatch = async () => {
  const res = await getMultiMatchApi({
    keywords: inpVal.value,
  });
  console.log("歌曲信息：", res.data);
  singerHurdle.value = res.data.result?.artist;
  songHurdle.value = res.data.result?.playlist;
  collectionHurdle.value = res.data.result?.album;
};
const getCloudSearch = async () => {
  const res = await getCloudSearchApi({
    keywords: inpVal.value,
  });
  console.log("歌曲列表：", res.data);
  blockList.value = res.data.result?.songs;
};

onMounted(async () => {
  await getHotSearch(); // 热门搜索
  isShowLoadingHotSearch.value = false;
  // 当输入框有值时，且点击搜索到的数据后，才进行搜索
  if (inpVal.value != "") {
    await getMultiMatch(); // 歌曲信息
    await getCloudSearch(); // 歌曲列表
  }
});

// 在搜索框输入后，热门搜索隐藏，搜索信息显示
function handleInput(event) {
  inpVal.value = event.target.value;
  console.log("输入的值：", inpVal.value);
  localStorage.setItem(LOCALSTORAGE_KEY, JSON.stringify(inputHistory.value));
  // 字符串对字符串
  if (inpVal.value != "") {
    isShow.value = false;
    getSearch(inpVal.value);
  } else {
    isShow.value = true;
  }
  // 使用计算属性来限制输入值的长度
  if (inpVal.value.length > maxLength) {
    inpVal.value = inpVal.value.slice(0, maxLength);
  }
}
// 按回车，进行搜索
function enter(event) {
  inpVal.value = event.target.value;
  console.log("进行搜索：", inpVal.value);
  inputHistory.value = JSON.parse(
    localStorage.getItem(LOCALSTORAGE_KEY) || "[]"
  );
  if (inpVal.value && !inputHistory.value.includes(inpVal.value)) {
    inputHistory.value.push(inpVal.value);
    localStorage.setItem(LOCALSTORAGE_KEY, JSON.stringify(inputHistory.value));
  }
  if (inpVal.value != "") {
    isShow.value = false;
    showContent.value = true;
    isShowLoadingSearchList.value = false;
    getMultiMatch(inpVal.value);
    getCloudSearch(inpVal.value);
  } else {
    isShow.value = true;
    showContent.value = false;
    isShowLoadingSearchList.value = true;
  }
}
// 点击搜索并添加进历史记录
function search(hots, allMatch, input) {
  inpVal.value = hots || allMatch.keyword || input;
  console.log(inpVal.value);
  inputHistory.value = JSON.parse(
    localStorage.getItem(LOCALSTORAGE_KEY) || "[]"
  );
  if (inpVal.value && !inputHistory.value.includes(inpVal.value)) {
    inputHistory.value.push(inpVal.value);
    localStorage.setItem(LOCALSTORAGE_KEY, JSON.stringify(inputHistory.value));
  }
  if (inpVal.value != "") {
    isShow.value = false;
    showContent.value = true;
    isShowLoadingSearchList.value = false;
    getMultiMatch(inpVal.value);
    getCloudSearch(inpVal.value);
  } else {
    isShow.value = true;
    showContent.value = false;
    isShowLoadingSearchList.value = true;
  }
}

// 点击x号，删除搜索内容
function clearInput() {
  inpVal.value = "";
  if (inpVal.value != "") {
    isShow.value = false;
    showContent.value = true;
    getSearch(inpVal.value);
  } else {
    isShow.value = true;
    showContent.value = false;
  }
}
// 点击x号，删除单条历史记录
function clearHistory(index) {
  inputHistory.value.splice(index, 1);
  localStorage.setItem(LOCALSTORAGE_KEY, JSON.stringify(inputHistory.value));
}

const singerList = (index) => {
  console.log("跳转到歌手页");
  router.push(`/artistPage?id=${singerHurdle.value[index].id}`);
  console.log(singerHurdle.value[index].id);
};
const songList = (index) => {
  console.log("跳转到歌曲页");
  router.push(`/musicList?id=${songHurdle.value[index].id}`);
  console.log(songHurdle.value[index].id);
};
const collection = (index) => {
  console.log("跳转到专辑页");
  router.push(`/collectionPage?id=${collectionHurdle.value[index].id}`);
  console.log(collectionHurdle.value[index].id);
};

</script>
  
<style lang="scss" scoped>
.search {
  position: relative;
  display: block;
  justify-content: center;
  align-items: center;
  padding: 15px 10px;
  border-bottom: 1px solid #eee;
  .my_search {
    display: block;
    .icon {
      position: absolute;
      top: 23px;
      left: 20px;
      bottom: 0;
      width: 30px; /* 图标的宽度 */
      background: none;
      border: none;
      color: #999; /* 图标颜色 */
      font-size: 16px;
      cursor: pointer;
    }
    .input {
      border: 0;
      outline: none;
      width: 100%;
      height: 32px;
      line-height: 30px;
      background: #f5f5f5;
      border-radius: 20px;
      padding-left: 30px;
      padding-right: 26px;
      padding-top: 2px;
      box-sizing: border-box;
    }
    .input::placeholder {
      color: #909090;
      font-size: 15px;
    }
    /* 当input获得焦点时的placeholder颜色 */
    #myInput:focus::placeholder {
      color: #d3d4da;
      font-size: 15px;
    }
    button {
      position: absolute;
      top: 2px;
      right: 12px;
      bottom: 0;
      width: 30px; /* 图标的宽度 */
      background: none;
      border: none;
      color: #999; /* 图标颜色 */
      font-size: 16px;
      cursor: pointer;
    }
  }
  .my_search:hover {
    background-color: #fff;
    border: 1px solid #d43c33;
    border-radius: 32px;
  }
}

.hot-search {
  padding: 15px 10px 0 10px;
  .title {
    font-size: 12px;
    line-height: 12px;
    color: #666;
  }
  .wrapper {
    display: block;
    margin: 10px 0 7px 0;
    .song-title {
      display: inline-block;
      height: 32px;
      margin-right: 8px;
      margin-bottom: 8px;
      padding: 0 14px;
      font-size: 14px;
      line-height: 32px;
      color: #333;
      border: 1px solid #d3d4da;
      border-radius: 32px;
    }
  }
}

.search-list {
  .name {
    height: 50px;
    margin-left: 10px;
    margin-bottom: 10px;
    padding-right: 15px;
    font-size: 15px;
    color: #507daf;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #eee;
  }
  .list {
    display: flex;
    justify-content: space-between;
    flex: 1;
    .icon {
      position: relative;
      top: 0;
      left: 0;
      bottom: 0;
      width: 20px; /* 图标的宽度 */
      background: none;
      border: none;
      color: #999; /* 图标颜色 */
      font-size: 16px;
      cursor: pointer;
    }
    .info {
      flex: 1;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #eee;
      padding-bottom: 5px;
      margin: 6px 10px 6px 20px;
      width: 100%;
      height: 100%;
      font-size: 14px;
      color: #333;
    }
  }
  .mistake {
    display: flex;
    justify-content: space-between;
    margin-left: 10px;
    font-size: 14px;
    color: #333;
  }
}

.bestFit {
  display: block;
  padding: 0 15px;
  .title {
    font-size: 12px;
    line-height: 12px;
    color: #666;
  }
  .singer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: 1;
    padding: 10px 0;
    border-bottom: 1px solid #eee;
    .icon {
      width: 50px;
      height: 50px;
      margin-right: 16px;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .name {
      font-size: 16px;
      color: #333;
      flex: 1;
    }
    .enter {
      display: flex;
      justify-content: right;
      align-items: center;
      width: 30px;
      height: 50px;
    }
  }
  .song {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: 1;
    padding: 10px 0;
    border-bottom: 1px solid #eee;
    .icon {
      width: 50px;
      height: 50px;
      margin-right: 16px;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .name {
      font-size: 16px;
      color: #333;
      flex: 1;
      .author {
        margin-top: 8px;
        margin-bottom: 4px;
        font-size: 14px;
        color: #999;
      }
    }
    .enter {
      display: flex;
      justify-content: right;
      align-items: center;
      width: 30px;
      height: 50px;
    }
  }
  .collection {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex: 1;
    padding: 10px 0;
    border-bottom: 1px solid #eee;
    .icon {
      width: 50px;
      height: 50px;
      margin-right: 16px;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .name {
      font-size: 16px;
      color: #333;
      flex: 1;
      .author {
        margin-top: 8px;
        margin-bottom: 4px;
        font-size: 14px;
        color: #999;
      }
    }
    .enter {
      display: flex;
      justify-content: right;
      align-items: center;
      width: 30px;
      height: 50px;
    }
  }
}

.history {
  padding: 15px 10px 0 10px;
  .list {
    display: flex;
    justify-content: space-between;
    flex: 1;
    .icon {
      position: relative;
      top: 6px;
      bottom: 0;
      width: 20px; /* 图标的宽度 */
      background: none;
      border: none;
      color: #999; /* 图标颜色 */
      font-size: 16px;
      cursor: pointer;
    }
    .record {
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #eee;
      padding-bottom: 5px;
      margin: 6px 10px;
      width: 100%;
      height: 100%;
      .my-record {
        width: 300px;
        font-size: 14px;
        color: #333;
        white-space: nowrap; /* 禁止换行 */
        overflow: hidden; /* 超出部分隐藏 */
        text-overflow: ellipsis; /* 使用省略号表示超出部分 */
        text-align: left; /* 文本对齐方式 */
      }
      button {
        position: relative;
        bottom: 0;
        width: 30px; /* 图标的宽度 */
        background: none;
        border: none;
        color: #999; /* 图标颜色 */
        font-size: 16px;
        cursor: pointer;
      }
    }
  }
}
</style>